package com.boyicloud.exchangeserver.web.sevice

import com.boyicloud.exchangeserver.common.DataBase
import com.boyicloud.exchangeserver.common.ExchangeParam
import com.boyicloud.exchangeserver.common.ListResp
import com.boyicloud.exchangeserver.domain.ClientInfo
import org.springframework.stereotype.Service

@Service
class ClientService {

    /**
     * 获取设备列表和软件列表
     */
    fun list(): ListResp {
        val equipmentList: List<ClientInfo> = DataBase.equipmentListMap.values.toList()
        val softwareList: List<ClientInfo> = DataBase.softwareListMap.values.toList()
        return ListResp(equipmentList, softwareList)
    }

    /**
     * 全部下线
     */
    fun reset() {
        DataBase.penetrateMap.clear()
        DataBase.equipmentListMap.forEach { it.value.channel.close() }
        DataBase.softwareListMap.forEach { it.value.channel.close() }
        DataBase.equipmentListMap.clear()
        DataBase.softwareListMap.clear()
    }

    /**
     * 只断开连接，不下线
     */
    fun disconnect(id: Long): ClientInfo {
        val filter = DataBase.equipmentListMap.values.first { it.id == id }
        val channel = DataBase.penetrateMap[filter.channel.id()]
        channel?.let { DataBase.penetrateMap.remove(it.id()) }
        DataBase.penetrateMap.remove(filter.channel.id())
        filter.remark = ""
        return filter
    }

    /**
     * 建立透传关系
     */
    fun exchange(exchangeParam: ExchangeParam) {
        //1、查找设备和软件
        val equipment = DataBase.equipmentListMap.values.first { it.id == exchangeParam.equipmentId }
        val software = DataBase.softwareListMap.values.first { it.id == exchangeParam.softwareId }
        //2、确认之前是否有与软件关联的透传 取消关系、移除备注
        if (DataBase.penetrateMap.containsKey(software.channel.id())) {
            val originalChannel = DataBase.penetrateMap[software.channel.id()]
            originalChannel?.let {
                val originalEquipment =
                    DataBase.equipmentListMap[originalChannel.id()]
                DataBase.penetrateMap.remove(originalChannel.id())
                originalEquipment?.remark = ""
            }
        }
        //3、创建关系
        DataBase.penetrateMap[equipment.channel.id()] = software.channel
        DataBase.penetrateMap[software.channel.id()] = equipment.channel
        equipment.remark = "与[${software.ip}:${software.port}]建立透传关系"
    }

    /**
     * 批量下线
     */
    fun offline(ids: Array<Long>) {
        ids.forEach { id ->
            val filter = disconnect(id)
            filter.channel.close()
            DataBase.equipmentListMap.remove(filter.channel.id())
        }
    }
}